﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecipeBookBusiness
{
    public class Comment
    {
        private RecipeBookEntities _entities = new RecipeBookEntities();
        private int _id;
        private int _recipeID;
        private int _userID;
        private string _commentText;

        public Comment(int commentID)
        {
            loadCommentClass(commentID);
        }

        public Comment(int recipeID, int userID, string commentText)
        {
            try
            {
                CommentDataRow cdr = new CommentDataRow();
                cdr.IDRecipe = recipeID;
                cdr.IDUser = userID;
                cdr.Text = commentText;

                //Save to DB and get ID
                _entities.AddToCommentDataRowSet(cdr);
                _entities.SaveChanges();
                int newCommentID = 0;
                foreach (CommentDataRow idCdr in _entities.CommentDataRowSet)
                {
                    if (idCdr.ID > newCommentID)
                        newCommentID = idCdr.ID;
                }
                loadCommentClass(newCommentID);
            }
            catch (Exception ex)
            {
                //TODO: Real exception handling
                Console.Write(ex.Message);
            }
        }

        private void loadCommentClass(int commentID)
        {
            CommentDataRow commentDR = (from c in _entities.CommentDataRowSet
                                     where c.ID == commentID
                                     select c).FirstOrDefault();
            _id = commentDR.ID;
            _recipeID = commentDR.IDRecipe;
            _userID = commentDR.IDUser;
            _commentText = commentDR.Text;
        }

        public void DeleteComment()
        {
            CommentDataRow cdr = (from c in _entities.CommentDataRowSet
                                 where c.ID == _id
                                 select c).FirstOrDefault();
            _entities.DeleteObject(cdr);
            _entities.SaveChanges();
        }

        public int ID
        {
            get
            {
                return _id;
            }
        }

        public int RecipeID
        {
            get
            {
                return _recipeID;
            }
        }

        public int UserID
        {
            get
            {
                return _userID;
            }
        }

        public string CommentText
        {
            get
            {
                return _commentText;
            }
        }
    }
}
